<?php

namespace App\Service;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class ZhipuAIService
{
    protected $client;
    protected $apiKey;
    protected $baseUri;
    protected $model;
    // 637920b10eca7fd23edec52e04b614c4.PT1jmBLxSe9Q5ZcU
    /**
     * Constructor
     *
     * @param string $apiKey API key for authorization
     * @param string $baseUri Base URI for the API
     */
    public function __construct(string $apiKey = '637920b10eca7fd23edec52e04b614c4.PT1jmBLxSe9Q5ZcU', string $baseUri = 'https://open.bigmodel.cn/api/paas/v4/')
    {
        $this->apiKey = $apiKey;
        $this->baseUri = $baseUri;
        $this->client = new Client([
            'base_uri' => $this->baseUri,
        ]);
    }

    /**
     * Set the API key
     *
     * @param string $apiKey API key for authorization
     */
    public function setApiKey($apiKey)
    {
        $this->apiKey = $apiKey;

    }

    /**
     * @param string $type
     * @return $this
     */
    public function setType(string $type = '')
    {
        $config = config('free');
        $typeConfig = $config[$type];
        $this->apiKey = $typeConfig['key'];
        $this->baseUri = $typeConfig['url'];
        $this->client = new Client([
            'base_uri' => $this->baseUri,
        ]);
        $this->model = $typeConfig['model'];

        return $this;
    }

    public function chat(array $data)
    {
        try {
            if ($this->model) {
                $data['model'] = $this->model;
            }
            $response = $this->client->post('chat/completions', [
                'headers' => [
                    'Authorization' => 'Bearer '.$this->apiKey,
                    'Content-Type'  => 'application/json',
                ],
                'json'    => $data,

            ]);

            return json_decode($response->getBody()->getContents(), true);
        } catch (RequestException $e) {
            throw new \Exception('Request to OpenAI failed: '.$e->getMessage());
        }
    }

    /**
     * @param $url
     * @param $postData
     * @param $headers
     * @return mixed
     */
    public function sendPostRequest($url, $postData, $headers = [])
    {
        // 初始化 cURL 会话
        $ch = curl_init();
        // 将数据编码为 JSON
        $jsonData = json_encode($postData);

        // 设置 cURL 选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); // 使用 JSON 数据
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将 cURL 的输出返回为字符串而不是直接输出


        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // 执行 cURL 请求并获取响应
        $response = curl_exec($ch);

        // 检查是否发生错误
        if (curl_errno($ch)) {
            // 如果发生错误，返回错误信息
            $error = curl_error($ch);
            curl_close($ch);
            throw new Exception("cURL Error: $error");
        }

        // 获取 HTTP 状态码
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        // 关闭 cURL 会话
        curl_close($ch);

        return json_decode($response, true);
        // return [
        //     'status_code' => $httpCode,
        //     'response'    => json_decode($response,true),
        // ];
    }

}
